<script setup lang="ts">
import { fullUrl } from '@/utils/common'
import { orderType, pageUrl, safeBottom } from '@/utils/constants'
import {
  getCartOrderPreApi,
  getOrderPreApi,
  getRepurchaseOrderPreByOrderIdApi,
  postOrderApi,
} from '@/api/order'
import { useAddressStore } from '@/stores/modules/address'
import type { orderPreResult } from '@/types/order'
import { onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import shopCoupon from '@/components/shop-coupon/shop-coupon.vue'
import type { couponListItem } from '@/types/coupon'
import { debounce } from 'lodash'
import { useMemberStore } from '@/stores'

//获取地址store
const addressStore = useAddressStore()
addressStore.changeScene('order')

const profileData = useMemberStore().profile

// 订单备注
const buyerMessage = ref('')

const disabledSubmit = ref(false)

if (!addressStore.selectedAddress?.id) {
  disabledSubmit.value = true
}

//获取页面参数
const query = defineProps<{
  sku_id?: string
  count?: string
  orderId?: string
}>()

//获取下单前信息
const orderPreData = ref<orderPreResult>()
const getOrderPreData = async () => {
  const params = {
    id: query.orderId ?? '0',
    sku_id: query.sku_id ?? '0',
    num: query.count ?? '0',
    address_id: addressStore.selectedAddress?.id ?? '0',
    coupon_id: selectCouponId.value ?? '0',
  }

  let res: any = []

  try {
    if (query.sku_id && query.count) {
      //直接下单
      res = await getOrderPreApi({
        sku_id: params.sku_id,
        num: params.num,
        address_id: params.address_id,
        coupon_id: params.coupon_id,
      })
    } else if (query.orderId) {
      //再次购买下单
      res = await getRepurchaseOrderPreByOrderIdApi({
        id: params.id,
        address_id: params.address_id,
        coupon_id: params.coupon_id,
      })
    } else {
      //购物车下单
      res = await getCartOrderPreApi({
        address_id: params.address_id,
        coupon_id: params.coupon_id,
      })
    }

    disabledSubmit.value = false
  } catch (error: any) {
    uni.showModal({
      title: '提示',
      content: error.data.msg,
    })
  }

  orderPreData.value = res.result

  if (res.result.error) {
    uni.showModal({
      title: '提示',
      content: res.result.error,
    })
    disabledSubmit.value = true
  }
}

//下单页收货地址
const addressData = computed(() => {
  return addressStore.selectedAddress
})

// 提交订单
const onOrderSubmit = async () => {
  await checkOrder()
}
// 订单提交前校验
const checkOrder = () => {
  if (!addressStore.selectedAddress?.id) {
    return uni.showToast({
      title: '请选择收货地址',
      icon: 'none',
      mask: true,
    })
  }
  debouncedSubmitOrder()
}
// 提交订单函数
const debouncedSubmitOrder = debounce(async () => {
  console.log('goods',orderPreData.value?.summary.total_price);
  const res = await postOrderApi({
    address_id: addressStore.selectedAddress!.id,
    remark: buyerMessage.value,
    goods: orderPreData.value!.goods.map((item) => ({
      sku_id: item.id,
      num: item.num,
    })),
    type: orderType.default,
    coupon_id: selectCouponId.value,
  })
   console.log('99999999',res);
  if (!res.result.id) {
    return uni.showToast({
      icon: 'error',
      title: '订单提交失败',
    })
  }
  uni.redirectTo({ url: `${pageUrl['order-pay']}?orderId=${res.result.id}&payPrice=${orderPreData.value?.summary.total_price}`})
  // 跳转详情
  //uni.redirectTo({ url: `${pageUrl['order-detail']}?id=${res.result.id}` })
}, 1000)

const couponPopup = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()
const openCouponPopup = () => {
  couponPopup.value?.open()
}
const closeCouponPopup = () => {
  couponPopup.value?.close()
}
const selectCouponId = ref<string | number>('')
const couponText = ref('')
// 选中优惠券
const selectCoupon = (item: couponListItem) => {
  selectCouponId.value = item.id
  getOrderPreData().then(() => {
    couponText.value = orderPreData.value!.summary.coupon_discount
    couponPopup.value?.close()
  })
}
// 清空已选择的优惠券
const clearSelectCoupon = () => {
  selectCouponId.value = ''
  getOrderPreData().then(() => {
    couponPopup.value?.close()
  })
}

onShow(() => {
  getOrderPreData()

  if (!profileData?.token) {
    addressStore.clearSelectedAddress()
  }
})
</script>

<template>
  <view v-if="orderPreData">
    <scroll-view scroll-y class="viewport">
      <!-- 收货地址 -->
      <navigator
        v-if="addressData"
        class="shipment"
        hover-class="none"
        :url="`${pageUrl['address']}?from=order`"
      >
        <view class="user"> {{ addressData.name }} {{ addressData.phone }} </view>
        <view class="address"> {{ addressData.full_location }} {{ addressData.address }} </view>
        <text class="icon icon-right"></text>
      </navigator>
      <navigator
        v-else
        class="shipment"
        hover-class="none"
        :url="`${pageUrl['address']}?from=order`"
      >
        <view class="address"> 请选择收货地址 </view>
        <text class="icon icon-right"></text>
      </navigator>

      <!-- 商品信息 -->
      <view class="goods" v-if="orderPreData">
        <navigator
          v-for="item in orderPreData?.goods"
          :key="item.sku_id"
          :url="`${pageUrl['goods-detail']}?id=${item.goods_id}`"
          class="item"
          hover-class="none"
        >
          <image class="picture" :src="fullUrl(item.image)" />
          <view class="meta">
            <view class="name ellipsis"> {{ item.goods.name }} </view>
            <view class="attrs">{{ item.spec_text }}</view>
            <view class="prices">
              <view class="pay-price symbol">{{ item.price }}</view>
              <view class="price symbol">{{ item.origin_price }}</view>
            </view>
            <view class="count">x{{ item.num }}</view>
          </view>
        </navigator>
      </view>

      <view class="related">
        <view class="item">
          <text class="text">订单备注</text>
          <input
            class="input"
            :cursor-spacing="30"
            placeholder="建议留言前先与商家沟通确认"
            v-model="buyerMessage"
          />
        </view>
      </view>

      <!-- 支付金额 -->
      <view class="settlement">
        <view class="item">
          <text class="text">商品总价: </text>
          <text class="number symbol">{{ orderPreData?.summary.total_price }}</text>
        </view>
        <view class="item">
          <text class="text">优惠券: </text>
          <text class="coupon" @tap="openCouponPopup" v-if="orderPreData.coupon_list.length > 0">
            <text v-if="selectCouponId" class="danger">-￥{{ couponText }}</text>
            <text v-else>
              <text class="danger">{{ orderPreData.coupon_list.length }}</text> 张优惠券可用
            </text>
          </text>
          <text v-else>无优惠券可用</text>
        </view>
        <view class="item">
          <text class="text">运费: </text>
          <text class="number symbol">{{ orderPreData?.summary.freight }}</text>
        </view>
      </view>
    </scroll-view>

    <!-- 优惠券弹出层 -->
    <uni-popup ref="couponPopup" type="share" background-color="#fff" class="coupon-popup">
      <view class="coupon-panel">
        <text class="close icon-close" @tap="closeCouponPopup"></text>
        <view class="title">选择优惠券</view>
        <view class="content">
          <shop-coupon
            :couponList="orderPreData.coupon_list"
            mode="user"
            buttonTitle="选择使用"
            @buttonClicked="selectCoupon"
            class="user-coupon-popup"
          />
        </view>
      </view>
      <view class="coupon-panel-footer">
        <view class="button primary" @tap="clearSelectCoupon"> 不使用优惠券</view>
      </view>
    </uni-popup>

    <!-- 底部占位空盒子 -->
    <view class="toolbar-height"></view>

    <!-- 吸底工具栏 -->
    <view class="toolbar" :style="safeBottom">
      <view class="total-pay symbol">
        <text class="number">{{ orderPreData?.summary.pay_price }}</text>
      </view>
      <view
        class="button"
        :class="{ disabled: disabledSubmit }"
        @tap="onOrderSubmit"
        :style="safeBottom"
      >
       <button class="button" :disabled="disabledSubmit">提交订单</button>
      </view>
      <!-- <button
        class="button"
        @tap="onOrderSubmit"
        :style="safeBottom"
        :class="{ disabled: disabledSubmit }"
        :disabled="disabledSubmit"
      >
        提交订单
      </button> -->
    </view>
  </view>
</template>

<style lang="scss">
page {
  display: flex;
  flex-direction: column;
  background-color: #f4f4f4;
}

.symbol::before {
  content: '¥';
  font-size: 80%;
  margin-right: 5rpx;
}

.shipment {
  margin: 20rpx;
  padding: 30rpx 30rpx 30rpx 84rpx;
  font-size: 26rpx;
  border-radius: 10rpx;
  background: url('~@/static/images/locate.png') 20rpx center / 50rpx no-repeat #fff;
  position: relative;

  .icon {
    font-size: 36rpx;
    color: #333;
    transform: translateY(-50%);
    position: absolute;
    top: 50%;
    right: 20rpx;
  }

  .user {
    color: #333;
    margin-bottom: 5rpx;
  }

  .address {
    color: #666;
    width: 94%;
  }
}

.goods {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    padding: 30rpx 0;
    border-top: 1rpx solid #eee;

    &:first-child {
      border-top: none;
    }

    .picture {
      width: 170rpx;
      height: 170rpx;
      border-radius: 10rpx;
      margin-right: 20rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      position: relative;
    }

    .name {
      font-size: 26rpx;
      color: #444;
    }

    .attrs {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 6rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
      max-width: 90%;
    }

    .prices {
      display: flex;
      align-items: baseline;
      margin-top: 6rpx;
      font-size: 28rpx;

      .pay-price {
        margin-right: 10rpx;
        color: #cf4444;
      }

      .price {
        font-size: 24rpx;
        color: #999;
        text-decoration: line-through;
      }
    }

    .count {
      position: absolute;
      bottom: 50;
      right: 0;
      font-size: 26rpx;
      color: #444;
    }
  }
}

.related {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .input {
    flex: 1;
    text-align: right;
    margin: 20rpx 0;
    padding-right: 20rpx;
    font-size: 26rpx;
    color: #999;
  }

  .item .text {
    width: 125rpx;
  }

  .picker {
    color: #666;
  }

  .picker::after {
    content: '\e6c2';
  }
}

/* 结算清单 */
.settlement {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;
  // padding-bottom: 200rpx;

  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .coupon {
    &::after {
      font-family: 'iconfont' !important;
      content: '\e6c2';
    }
  }

  .danger {
    color: #cf4444;
  }
}

.coupon-panel {
  .title {
    line-height: 1;
    padding: 40rpx 0;
    text-align: center;
    font-size: 32rpx;
    font-weight: normal;
    border-bottom: 1rpx solid #ddd;
    color: #444;
  }

  .close {
    position: absolute;
    right: 24rpx;
    top: 24rpx;
    font-size: 40rpx;
  }

  .content {
    min-height: 400rpx;
    max-height: 650rpx;
    overflow: auto;
    -webkit-overflow-scrolling: touch;
  }
}

.coupon-panel-footer {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 0 40rpx;
  font-size: 28rpx;
  color: #444;

  .button {
    flex: 1;
    height: 72rpx;
    text-align: center;
    line-height: 72rpx;
    margin: 0 20rpx;
    color: #fff;
    border-radius: 72rpx;
  }

  .primary {
    color: #fff;
    background-color: #ff5f3c;
  }

  .secondary {
    background-color: #ffa868;
  }
}

/* 吸底工具栏 */
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(var(--window-bottom));
  z-index: 1;

  background-color: #fff;
  height: 100rpx;
  padding: 0 20rpx;
  border-top: 1rpx solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: content-box;

  .total-pay {
    font-size: 40rpx;
    color: #cf4444;

    .decimal {
      font-size: 75%;
    }
  }

  .button {
    width: 220rpx;
	height: 72rpx;
    text-align: center;
    font-size: 26rpx;
    color: #fff;
    border-radius: 22rpx;
    background-color: #ff5f3c;
  }

  .disabled {
    opacity: 0.6;
  }
}

// 底部占位空盒子
.toolbar-height {
  height: 190rpx;
}
</style>
